package com.hanbang.mrcm.aboutme;

import java.io.File;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.hanbang.mrcm.R;
import com.hanbang.mrcm.application.MyApplication;
import com.hanbang.mrcm.base.MainBaseActivity;
import com.hanbang.mrcm.home.HomeActivity;
import com.hanbang.mrcm.merchant.MerchantActivity;
import com.hanbang.mrcm.myview.MyDialog;
import com.hanbang.mrcm.myview.MyDialog.MODE;
import com.hanbang.mrcm.myview.MyDialog.OnClickCallback;
import com.hanbang.mrcm.utils.HttpInterfaces;
import com.hanbang.mrcm.utils.MyRequestCallBack;
import com.hanbang.mrcm.utils.MyToast;
import com.hanbang.mrcm.utils.SystemTools;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class AboutMeActivity extends MainBaseActivity {

	// 拍完照存放的名称
	private String camera = "capture.jpg";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aboutme);
		bitmapUtils.configDefaultLoadFailedImage(R.drawable.default_portrait2);
		initView();
		setOnClickListener();
	}

	/*
	 * 设置点击事件
	 */
	private void setOnClickListener() {
		ViewGroup v1 = (ViewGroup) findViewById(R.id.bottom_bar_ll1);
		ViewGroup v2 = (ViewGroup) findViewById(R.id.bottom_bar_ll2);
		ViewGroup v3 = (ViewGroup) findViewById(R.id.bottom_bar_ll3);
		setBottonButton(v3);
		v1.setOnClickListener(onClickListener);
		v2.setOnClickListener(onClickListener);

		findViewById(R.id.my_head).setOnClickListener(onClickListener);
		findViewById(R.id.my_name).setOnClickListener(onClickListener);
		findViewById(R.id.my_cdker).setOnClickListener(onClickListener);
		findViewById(R.id.my_jifen).setOnClickListener(onClickListener);
		findViewById(R.id.my_message).setOnClickListener(onClickListener);
		findViewById(R.id.about_app).setOnClickListener(onClickListener);
		findViewById(R.id.feedback).setOnClickListener(onClickListener);
		findViewById(R.id.text_button_eixt).setOnClickListener(onClickListener);

	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			switch (v.getId()) {
			case R.id.bottom_bar_ll1:
				intent.setClass(AboutMeActivity.this, HomeActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				break;
			case R.id.bottom_bar_ll2:
				intent.setClass(AboutMeActivity.this, MerchantActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				break;
			case R.id.text_button_eixt:
				if (isLogin(false)) {
					passwordIsError(false);
					userData = null;
					// 头像
					((ImageView) findViewById(R.id.my_head))
							.setImageResource(R.drawable.default_portrait);
					// 昵称
					((TextView) findViewById(R.id.my_name)).setText("登录");
					MyToast.show(AboutMeActivity.this, "注销成功",
							Toast.LENGTH_SHORT);
				}
				break;
			case R.id.my_cdker:
				if (!isLogin(true)) {
					break;
				}
				intent.setClass(AboutMeActivity.this, MyCdkerActivity.class);
				startActivity(intent);
				break;
			case R.id.my_jifen:
				if (!isLogin(true)) {
					break;
				}
				intent.setClass(AboutMeActivity.this, MyIntegralActivity.class);
				startActivity(intent);
				break;
			case R.id.my_message:
				if (!isLogin(true)) {
					break;
				}
				intent.setClass(AboutMeActivity.this, MyMessageActivity.class);
				startActivity(intent);
				break;
			case R.id.about_app:
				intent.setClass(AboutMeActivity.this, AboutAppActivity.class);
				startActivity(intent);
				break;
			case R.id.feedback:
				if (!isLogin(true)) {
					break;
				}
				intent.setClass(AboutMeActivity.this, FeedbackActivity.class);
				startActivity(intent);
				break;
			case R.id.my_name:
				if (!isLogin(true)) {
					break;
				}
				MyDialog dialog0 = new MyDialog(AboutMeActivity.this,
						R.style.base_dialog, MODE.EDITTEXT);
				dialog0.setTitle("修改昵称");
				dialog0.setOnClickCallback(new MyDialog.OnClickCallback() {

					@Override
					public void onClick(MyDialog dialog, Object number,
							Object content) {
						if ((Integer) number == 2) {
							upUserName(content == null ? null : content
									.toString());
						}

					}

				});
				dialog0.show();

				break;
			case R.id.my_head:
				if (!isLogin(true)) {
					break;
				}
				MyDialog dialog = new MyDialog(AboutMeActivity.this,
						R.style.about_me_dialog, MODE.HEAD);
				dialog.setOnClickCallback(new OnClickCallback() {
					@Override
					public void onClick(MyDialog dialog, Object number,
							Object content) {
						// 拍照
						if ((Integer) number == 1) {
							File fDir = new File(MyApplication.picFilepath);
							if (fDir.exists() || fDir.mkdirs()) {
								File cameraFile = new File(fDir, camera);
								if (!cameraFile.exists()) {
									try {
										cameraFile.createNewFile();
									} catch (IOException e) {
										e.printStackTrace();
									}
								}
								Intent intent = new Intent(
										MediaStore.ACTION_IMAGE_CAPTURE);
								intent.putExtra(MediaStore.EXTRA_OUTPUT,
										Uri.fromFile(cameraFile));
								startActivityForResult(intent, 998);
							}
							// 相册选择
						} else if ((Integer) number == 2) {
							// 获取相册
							Intent intent = new Intent();
							intent.setType("image/*");
							intent.setAction(Intent.ACTION_GET_CONTENT);
							intent.putExtra("return-data", true);
							startActivityForResult(intent, 999);
						}
					}
				});

				dialog.show();
				break;
			default:
				break;
			}
		}
	};

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		/*
		 * 相册 resultCode: 正常返回-1 用户后退返回0
		 */

		if (requestCode == 999 && resultCode == -1) {
			Intent intent = new Intent(AboutMeActivity.this,
					ClipPhotoActivity.class);
			Uri uri = data.getData();
			intent.putExtra("path",
					SystemTools.getPath(AboutMeActivity.this, uri));
			startActivityForResult(intent, 1000);
		}
		/*
		 * 相片裁剪界面发过来的
		 */
		if (requestCode == 1000 && resultCode == 1000) {
			String p = data.getStringExtra("path");
			upDataPortrait(p);
		}
		// 拍照返回的数据
		if (requestCode == 998 && resultCode == -1) {
			Intent intent = new Intent(AboutMeActivity.this,
					ClipPhotoActivity.class);
			File fDir = new File(MyApplication.picFilepath);
			if (fDir.exists() || fDir.mkdirs()) {
				File cameraFile = new File(fDir, camera);
				if (cameraFile.exists()) {
					intent.putExtra("path", cameraFile.getPath());
					startActivityForResult(intent, 1000);
				} else {
					MyToast.show(AboutMeActivity.this, "获取照片失败！",
							Toast.LENGTH_SHORT);
				}
			} else {
				MyToast.show(AboutMeActivity.this, "获取照片失败！",
						Toast.LENGTH_SHORT);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	};

	/*
	 * 初始化view
	 */
	private void initView() {
		// 设置顶部的标题
		setTitle(findViewById(R.id.top_bar_title),
				getString(R.string.botton_tab3));
		upDataTouxiangAndNice();

	}

	private void upDataTouxiangAndNice() {
		if (userData != null) {
			// 头像
			bitmapUtils.display(findViewById(R.id.my_head),
					SystemTools.getHttpFileUrl(userData.getAvatar()));
			// 昵称
			((TextView) findViewById(R.id.my_name)).setText(userData
					.getNickname());
		} else {
			// 头像
			((ImageView) findViewById(R.id.my_head))
					.setImageResource(R.drawable.default_portrait);
			// 昵称
			((TextView) findViewById(R.id.my_name)).setText("登录");
		}
	}

	/*
	 * 更新昵称
	 */
	private void upUserName(final String name) {
		if (!isLogin(true)) {
			return;
		}
		if (name == null || name.trim().equals("")) {
			MyToast.show(this, "请填写昵称", Toast.LENGTH_SHORT);
			return;
		}
		httpUtils.send(
				HttpMethod.GET,
				HttpInterfaces.userUpdateNick + "&mobile="
						+ userData.getMobile() + "&password="
						+ userData.getPassword() + "&nickname=" + name,
				new MyRequestCallBack<String>(this,
						getString(R.string.loadding)) {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int status = json.getInt("status");
							if (status == 1) {
								userData.setNickname(name);
								setDbUserData();
								// 昵称
								((TextView) findViewById(R.id.my_name))
										.setText(name);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	/*
	 * 上传头像
	 */
	private void upDataPortrait(String path) {
		File f = new File(path);
		if (f.exists() && isLogin(false)) {
			RequestParams params = new RequestParams();
			params.addBodyParameter("action", "user_update_head");
			params.addBodyParameter("mobile", userData.getMobile());
			params.addBodyParameter("password", userData.getPassword());
			params.addBodyParameter("avatar", f);
			((MyApplication) getApplicationContext()).httpUtils.send(
					HttpMethod.POST, HttpInterfaces.userLogin, params,
					new MyRequestCallBack<String>(this,
							getString(R.string.loadding)) {
						@Override
						public void onFailure(HttpException error, String msg) {
							super.onFailure(error, msg);
							// 失败
						}

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							super.onSuccess(responseInfo);
							try {
								JSONObject json = new JSONObject(
										responseInfo.result);
								if (json.getInt("status") == 1) {
									String path = json.getString("path");
									userData.setAvatar(path);
									setDbUserData();
									// 头像
									bitmapUtils.display(
											findViewById(R.id.my_head),
											SystemTools.getHttpFileUrl(userData
													.getAvatar()));
								}
							} catch (JSONException e) {
								e.printStackTrace();
								// 失败
							}
						}
					});
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		bitmapUtils.configDefaultLoadFailedImage(R.drawable.default_portrait2);
		upDataTouxiangAndNice();

	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
